<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="rules">
      <el-form-item prop="mobile">
        <el-input v-model="loginForm.mobile" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    const validateMobileFun = (rule, value, callback) => {
      const r = /^1[3-9]\d{9}$/.test(value);
      r ? callback() : callback(new Error('手机号格式不对'));
    };
    return {
      loginForm: {
        mobile: '13800000002',
        password: '123456',
      },
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobileFun },
        ],
        password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
      },
    };
  },
  methods: {
    handleLogin() {
      // this.$store.dispatch是分发action的方法
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            this.$router.push('/');
          });
        } else {
          this.$message({
            message: '格式校验失败，请重新填写',
            type: 'warning',
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.login-container {
  width: 60%;
  margin: 100px auto 0;
}
</style>
